import 'package:permission_handler/permission_handler.dart';

class PermissionHelper {
  static final PermissionHelper _permissionHelper = PermissionHelper._internal();

  factory PermissionHelper.instance() {
    return _permissionHelper;
  }

  PermissionHelper._internal();

  ///请求权限
  Future<Map<PermissionGroup, PermissionStatus>> requestPermission(List<PermissionGroup> permissions) async {
    return await PermissionHandler().requestPermissions(permissions);
  }

  ///检查权限是否都被授予
  Future<bool> checkPermissionsHasGranted(List<PermissionGroup> permissions) async {
    var hasGranted = true;
    for (int i = 0; i < permissions.length; i++) {
      PermissionStatus status = await PermissionHandler().checkPermissionStatus(permissions[i]);
      if (status != PermissionStatus.granted) {
        hasGranted = false;
      }
    }
    return hasGranted;
  }

  ///检查服务的状态
  Future<ServiceStatus> checkServiceStatus() async {
    ServiceStatus serviceStatus = await PermissionHandler().checkServiceStatus(PermissionGroup.location);
    return serviceStatus;
  }

  ///打开设置页面
  openSetting() async {
    bool isOpened = await PermissionHandler().openAppSettings();
  }

  ///检测权限是否可以动态申请
  Future<bool> shouldShowRequestPermissionRationale(List<PermissionGroup> permissions) async {
    var shouldShowRequestPermissionRationale = true;
    for (int i = 0; i < permissions.length; i++) {
      bool status = await PermissionHandler().shouldShowRequestPermissionRationale(permissions[i]);
      if (!status) {
        var status = await PermissionHandler().checkPermissionStatus(permissions[i]);
        if (status != PermissionStatus.granted) shouldShowRequestPermissionRationale = false;
      }
    }
    return shouldShowRequestPermissionRationale;
  }
}
